import React,{useEffect,useState} from 'react'
import { NavBarPlaySong } from '../../components/NavBar/NavBarPlaySong'
import './index.scss'
import {_getLyric,_getComment} from '../../api/recommend'
import {connect} from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { Flex , Slider } from 'react-vant'
import {changeTimeFormat,formatSeconds} from '../../utils/index'
import PopupSongList from '../../components/Popup/PopupSongList'
import { changeMusicSrcAsync,changeMusicControls,changePlayOrder,changeMusicCurrentDetail,changeMusicCurrentTime} from '../../store/actions/music'
function PlaySong(props) {
  const {musicCurrentDetail,musicControls,musicSrc,musicCurrentTime,musicNode,playOrder,musicList} = props
  const [openLrc,setOpenLrc] = useState(false)
  const [lrcList,setLrcList] =useState([])
  const [songListVisible,setSongListVisible] = useState(false)
  const navigator = useNavigate()
  //进度条
  const [value, setValue] = useState(0);
  const onChangeAfter = (v) => {
    props.changeMusicControls(false)
    musicNode.play()
  }
  const onChange = (v) => {
    props.changeMusicControls(true)
    musicNode.pause()
    let allTime = musicSrc.data.time/1000
    const currentTime = v*allTime/100
    musicNode.currentTime=currentTime
    props.changeMusicCurrentTime({
      ms:formatSeconds(currentTime,'m:s'),
      s:currentTime
    })
    setValue(v)
  }
  useEffect(()=>{
    if(!musicSrc.id) return navigator('/')
    let timer =null
    if(musicControls===false){
      let allTime = musicSrc.data.time/1000
      timer = setInterval(() => {
        let currentTime = musicNode.currentTime
        props.changeMusicCurrentTime({
          ms:formatSeconds(currentTime,'m:s'),
          s:currentTime
        })
        setValue(currentTime/allTime*100)
      }, 1000);
    }else {
      clearInterval(timer)
    }
    return () => clearInterval(timer);
  },[musicControls])
  // 初始化歌词
  useEffect(()=>{
    if(!musicSrc.id) return navigator('/')
    getLyric(musicSrc.id)
  },[])
  function getLyric(id){
    _getLyric(id).then(res=>{
      const lrcArr = handleLRC(res.lrc.lyric)
      setLrcList(lrcArr)
    })
  }
  //解析歌词
  function handleLRC(lrcArr){
    var lrc = String(lrcArr);
    if(lrc.length==0) return;
    var lyricsList = []; //存放歌词
    var lrcs = lrc.split('\n');//用回车拆分成数组
    lrcs.forEach((e)=>{
      let time = e.match(/\[\d{2,}:(\d{2})(?:\.(\d{2,3}))?]/g)
      if(time!=null){
        let content = e.split(time)[1]
        let timeReg = time[0].match(/(\d{2,}):(\d{2})(?:\.(\d{2,3}))?/)
        let timeSecond = parseInt(timeReg[1]) * 60 + parseInt(timeReg[2]) + parseInt(timeReg[3]) /
          1000
          lyricsList.push({
          content,
          time:timeSecond
        })
      }
    })
    return lyricsList;
  }
  //处理歌词
  function handleScrollLRC(){
    if(openLrc===false) return
    for(let i=0;i<lrcList.length;i++){
      let text = document.getElementsByClassName('lrc_li')
      let line = lrcList[i]
      let nextLine = lrcList[i + 1]
      let current = musicCurrentTime.s
      // /**如果歌曲currentTime大于当前行歌曲时间，并且，下一行不为空或者当前currentTime小于下一行时间 */
      if(current>=line.time && (!nextLine || current<nextLine.time)){
        text[i].scrollIntoView({
          behavior: 'smooth',
          block: 'center',
          inline: 'nearest' 
        })
      }
    }
  }
  useEffect(()=>{
    if(!musicSrc.id) return navigator('/')
    handleScrollLRC()
  },[musicCurrentTime.s])

  // 播放开关
  function changePlay(){
    musicControls===false ? musicNode.pause() : musicNode.play()
    props.changeMusicControls(!musicControls)
    
  }
  //上下曲
  function prevNextSong(flag){
    musicList.map((item,index)=>{
      if(musicSrc.id===item.id){
        let song = flag===true? 
        (index===0 ? musicList[musicList.length-1]:musicList[index-1]) : 
        ((index===musicList.length-1) ? musicList[0] : musicList[index+1])
        props.changeMusicSrcAsync(song.id)
        props.changeMusicCurrentDetail(song)
        getLyric(song.id)
      }
    })
    let timer = setInterval(() => {
      musicNode.oncanplay=()=>{
        musicNode.play()
        clearInterval(timer)
      }
    }, 10);
  }
  //关闭列表popup
  function closePopupSongList(){
    setSongListVisible(false)
  }

  return (musicSrc.id?(
    <div className='play_song'>
      <NavBarPlaySong songName={musicCurrentDetail.name} back={()=>navigator('/')} ar={musicCurrentDetail.ar.map(itm=>{return itm.name})}/>
      <img className='play_song_bg'alt='' src={musicCurrentDetail.al.picUrl}/>
      {openLrc===false?(
        <div className='play_song_center'>
          <div className='disk_switch'>
            <img className={[musicControls===true?'moveTo':''].join(' ')} src='https://s3.music.126.net/mobile-new/img/needle-ab.png' alt=''/>
          </div>
          <div className='disk'>
            <div className='songImg'>
              <img style={{animationPlayState:(musicControls===true)?'paused':'running'}} src={musicCurrentDetail.al.picUrl}/>
            </div>
            <img alt='' src='https://p5.music.126.net/obj/wo3DlcOGw6DClTvDisK1/4602256867/5855/63fb/325b/d7e4e3a244701ee85fecb5d4f6b5bd57.png?imageView=&quality=75&thumbnail=200y200'/>
          </div>
        </div>):(
          <div className='play_song_lrc'>
            {lrcList.map((item,index)=>{
              return<div key={index} className='lrc_li' style={{ color:index<lrcList.length-1 && musicCurrentTime.s>=item.time && musicCurrentTime.s<lrcList[index+1].time ||
                 index===lrcList.length-1 && musicCurrentTime.s>=item.time
                ?'#31c27c':'#FFF' }}>{item.content}</div>
            })}
          </div>
        )}
      <div className='play_song_control'>
        <Flex justify='around' align='center' className='play_song_control_top'>
          <span className='iconfont icon-shoucang'/>
          <span className='iconfont icon-geciweidianji'onClick={()=>setOpenLrc(!openLrc)}/>
          <span className='iconfont icon-pinglun-' onClick={()=>navigator('/comment')}/>
          <span className='iconfont icon-gengduo'/>
        </Flex>
        <div className='play_song_control_center'>
            <div className='time start_time'>{musicCurrentTime.s!==0?musicCurrentTime.ms:'00:00'}</div>
            <div className='time end_time'>{musicSrc.data?changeTimeFormat(musicSrc.data.time,'m:s'):''}</div>
            <div className='play_song_control_center_progress'>
              <Slider value={value} buttonSize={13} onChange={onChange} onChangeAfter={onChangeAfter} />
            </div>
        </div>
        <Flex justify='around' align='center'  className='play_song_control_bottom'>
          <span className={['iconfont',playOrder===0 ? 'icon-danquxunhuan':'icon-bofang-xunhuanbofang'].join(' ')} onClick={()=>props.changePlayOrder(playOrder===0?1:0)}/>
          <span className='iconfont icon-shangyishoushangyige' onClick={()=>prevNextSong(true)}/>
          <span className={['iconfont', musicControls===true?'icon-bofang2':'icon-bofang1'].join(' ')} onClick={changePlay}/>
          <span className='iconfont icon-xiayigexiayishou' onClick={()=>prevNextSong(false)}/>
          <span className='iconfont icon-24gf-playlist' onClick={()=>setSongListVisible(true)}/>
        </Flex>
      </div>
      <PopupSongList songListVisible={songListVisible} closePopupSongList={closePopupSongList}/>
    </div>):(<div>暂无歌曲在播放</div>)
  )
}
export default connect(
  state =>({
    musicCurrentDetail:state.musicCurrentDetail,
    musicControls:state.musicControls,
    musicSrc:state.musicSrc,
    musicCurrentTime:state.musicCurrentTime,
    musicNode:state.musicNode,
    playOrder:state.playOrder,
    musicList:state.musicList
  }),{
    changeMusicControls,
    changePlayOrder,
    changeMusicCurrentTime,
    changeMusicCurrentDetail,
    changeMusicSrcAsync
})(PlaySong)